/**
 * 淘宝店铺体验分数据port
 * 数据处理
 */

import moment from "moment"

import type { PlasmoMessaging } from "@plasmohq/messaging"

// 数据记录
let scoreData = {}
// 校验总键数
let totalKeys = 0
// 键名列表
let keysList = []

// 初始化数据
const initData = () => {
  scoreData = {}
}

// 更新scoreData
const updateScoreData = (data: any) => {
  scoreData = {
    ...scoreData,
    ...data
  }
}

// 数值处理
const formatValue = (value: number | string) => {
  // 过滤新店空值
  // 如果值为"-"，则返回"0"
  if (value === "-") {
    return "0"
  }
  return value
}

/*** 拦截数据处理器 ***/
// 匹配处理器
const dataMatcher = (
  matchApi: string,
  matchComponentId: string | undefined,
  matchData: any
) => {
  const { api, data } = matchData
  const { componentId } = data || {}
  if (matchComponentId) {
    // 如果有componentId，则需要匹配componentId
    return (
      String(api) === matchApi && String(componentId || "") === matchComponentId
    )
  } else {
    // 如果没有componentId，则只需要匹配api
    return String(api) === matchApi
  }
}
// 一级数据处理
const level1DataInspector = (api: string, data: any) => {
  // 处理目标匹配
  const matchApi = "mtop.alibaba.front.store.index"
  const matchComponentId = "storeIndicators"
  if (!dataMatcher(matchApi, matchComponentId, { api, data })) return
  // 数据处理
  const dataList = data?.dataSource?.list || []
  const tempData = {}
  dataList.forEach((item: any, idx: number) => {
    tempData[item?.name || `未知${idx}`] = formatValue(item?.score || "0")
  })
  updateScoreData(tempData)
}
// 日期数据处理
const dateInspector = (api: string, data: any) => {
  // 处理目标匹配
  const matchApi = "mtop.sdx.nps.home.benefits"
  if (!dataMatcher(matchApi, undefined, { api, data })) return
  // 数据处理
  const updateDate = data?.data?.updateDate || ""
  updateScoreData({ 日期: moment(updateDate).format("YYYY-MM-DD") })
}
// 二级数据处理
const level2DataInspector = (api: string, data: any) => {
  // 处理目标匹配
  const matchApi = "mtop.sdx.nps.home.indexsummary"
  if (!dataMatcher(matchApi, undefined, { api, data })) return
  // 数据处理
  const dataList = data?.data?.mainIndexInfoList || []
  const tempData = {}
  // 一级数据循环
  dataList.forEach((item: any, idx: number) => {
    // 二级数据循环
    const subDataList = item?.subIndexInfoList || []
    subDataList.forEach((subItem: any, subIdx: number) => {
      tempData[subItem?.name || `未知${idx}`] =
        formatValue(subItem?.showValue || "") + (subItem?.unit || "")
      // 新增得分数据记录
      tempData[(subItem?.name || `未知${idx}`) + "得分"] = formatValue(
        subItem?.score || "0"
      )
    })
  })

  updateScoreData(tempData)
}

// port handler
const handler: PlasmoMessaging.PortHandler = async (req, res) => {
  // console.log("TbShopScoreData port handler", req, res)
  const { api, data, action } = req.body
  switch (action) {
    case "clear":
      // 清空数据
      initData()
      break
    case "setKeys":
      // 设置数据键值总量
      // 设置数据键值总量
      totalKeys = data?.count || 0
      keysList = data?.fields || []
      break
    case "inspect":
      // 轮询处理拦截数据
      const inspectors = [
        level1DataInspector,
        dateInspector,
        level2DataInspector
      ]
      for (const inspector of inspectors) {
        inspector(api, data)
      }
      break
    default:
      break
  }
  //
  res.send({
    data: scoreData,
    keysList,
    rate: ((Object.keys(scoreData).length / totalKeys) * 100).toFixed(0)
  })
}

export default handler
